<script lang="tsx">
import { defineComponent, onMounted, reactive, ref, watch, nextTick } from 'vue';
import { ElPagination } from 'element-plus';
import { trimStringParams } from '#/utils/trimStringParams'
import { $t } from '@vben/locales';
import { getCertificationInfoForPersonCenterApi } from '#/api/personal/certification';
import { VbenIcon } from '@vben-core/shadcn-ui';
import { SvgCertificationIcon, SvgNoDataIcon } from '@vben/icons';
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'


// baseQuery通过全局注册使用，无需导入

export default defineComponent({
  name: 'PersonalCertification',
  setup() {
    const router = useRouter()
    // 查询数据
    const queryData = reactive({
      name: '',
      createTime: null
    });

    const pageData = reactive<any>({
      total: 10,
      curPage: 1,
      pageSize: 10
    })

    // 添加缺少的变量
    const loadingFlag = ref([0, 0, 0]); // 加载状态标志
    const tableData = ref([]); // 表格数据
    const loading = ref(false); // 页面加载状态

    // 查询配置
    const queryColumns = [
      {
        prop: 'name',
        label: $t('certification.certificationName'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('certification.certificationName')]),
        maxlength: 50
      },
      {
        prop: 'createTime',
        label: $t('certification.participationTime'),
        type: 'daterange',
        rangeSeparator: $t('common.rangeSeparatorTxt'),
        startPlaceholder: $t('common.startTimeTxt'),
        endPlaceholder: $t('common.endTimeTxt'),
        'value-format': 'YYYY-MM-DD HH:mm:ss',
        'default-time': [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]
      }
    ];

    // 分页相关方法
    const onSizeChange = (size: number) => {
      pageData.pageSize = size;
      pageData.curPage = 1;
      handleQuery();
    };

    const onCurrentChange = (page: number) => {
      pageData.curPage = page;
      handleQuery();
    };

    // 查询方法
    const handleQuery = () => {
      console.log('查询数据:', queryData);
      const params = {
        curPage: pageData.curPage,
        pageSize: pageData.pageSize
      } as any;
      const trimData = trimStringParams(queryData)
      console.log(trimData)
      Object.keys(trimData).forEach(key => {
        const kVal = trimData[key as keyof typeof trimData]
        if (key === 'createTime') {
          params.startTime = kVal?.[0]
          params.endTime = kVal?.[1]
        } else if (kVal) {
          params[key] = kVal
        }
      })
      loadingFlag.value[1] = 1;
      console.log(params)

      getCertificationInfoForPersonCenterApi(params).then((res: any) => {
        let { pageInfo, data = [] } = res
        pageData.total = pageInfo.totalRows
        tableData.value = data
      }).finally(() => {
        loadingFlag.value[1] = 0;
      })
    };

    // 重置方法
    const handleReset = () => {
      queryData.name = ''
      queryData.createTime = null
      nextTick(() => {
        handleQuery()
      })
    };

    const gotoCertification = (item: any) => {
      router.push(`/lesson/home/${item.certificationId}`)
    }

    watch(
      () => loadingFlag.value,
      (val: number[]) => {
        if (val) {
          const isLoading = val.some((i: number) => i === 1)
          loading.value = isLoading
        }
      },
      { deep: true },
    )

    onMounted(() => {
      handleQuery()
    })

    return () => (
      <div class="flex flex-col h-full bg-[#fff] p-[24px] pt-[16px] rounded-[8px]">
        {/* 查询区域 */}
        <div class="border-b border-gray-200 query pb-[6px]">
          <base-query
            columns={queryColumns}
            data={queryData}
            labelPosition="right"
            onClick={handleQuery}
            onReset={handleReset}
          />
        </div>

        {/* 内容区域 */}
        <div class="min-h-[1px] flex-1 overflow-y-auto p-[24px]" v-loading={loading.value}>
          {tableData.value?.length > 0 ? (
            <div class="h-auto grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-[26px]">
              {tableData.value?.map((item: any) => (
                <div key={item.certificationId} class="flex flex-col items-center pb-[24px] rounded-[16px] overflow-hidden bg-[#0067D10D] cursor-pointer" onClick={() => gotoCertification(item)}>
                  {/* icon */}
                  <VbenIcon icon={SvgCertificationIcon} class={`w-[88px] h-[88px] fill-transparent my-[40px]`} />

                  {/* 卡片内容 */}
                  <div class="text-center text-[#191919]">
                    {/* 第一行：认证名称 */}
                    <div class="text-[14px] font-medium leading-[22px] mb-2">
                      {item.name}
                    </div>

                    {/* 第二行：购买时间 */}
                    <div class="text-[14px] leading-[22px] text-[#595959]">
                      {dayjs(item.purchaseTime).format('YYYY-MM-DD HH:mm:ss')}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div class="w-full h-full flex flex-col items-center justify-center">
              <VbenIcon icon={SvgNoDataIcon} class={`w-[200px] h-[200px] fill-transparent mb-[10px]`} />
              <span class="text-[14px] leading-[22px] text-[#595959]">
                {$t('common.emptyTxt')}
              </span>
            </div>
          )}
        </div>

        {/* 分页区域 */}
        <ElPagination
          class="pagination pt-[15px]"
          size="small"
          layout="total, sizes, prev, pager, next, jumper"
          total={pageData.total}
          v-model:current-page={pageData.curPage}
          v-model:page-size={pageData.pageSize}
          pageSizes={[10, 20, 50, 100]}
          onSize-change={onSizeChange}
          onCurrent-change={onCurrentChange}
        />
      </div>
    );
  }
});
</script>
<style lang="less" scoped></style>
